package top.xxyu.file.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

import top.xxyu.common.util.SFTPUtils;
import top.xxyu.file.service.FileUtil;
import top.xxyu.file.service.IFileService;

/**
 * file
 * 
 * @author xx
 *
 */
@Controller
@RequestMapping(value = "/file")
public class FileController {

//	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private IFileService fileService;

	@RequestMapping("/upload")
	@ResponseBody
	public Map<String, Object> handleFileUpload(@RequestParam("file") MultipartFile multiparFile) throws IOException {
		String msg = "";
		Map<String, Object> map = new HashMap<>();
		if (!multiparFile.isEmpty()) {
			Map<String, Object> mapFile = FileUtil.getFileFromMultiparFile(multiparFile);
			// 获取文件名
			String realName = String.valueOf(mapFile.get(FileUtil.REAL_NAME));

			// 文件名字
			String fileUuidName = String.valueOf(mapFile.get(FileUtil.FILE_UUID_NAME));
			// 文件路径
			String filePath = String.valueOf(mapFile.get(FileUtil.FILE_PATH));

			File file = (File) mapFile.get(FileUtil.FILE);
			try {
				multiparFile.transferTo(file);
				try {
					SFTPUtils.uploadFile(filePath);
				} catch (SftpException e) {
					e.printStackTrace();
				} catch (JSchException e) {
					e.printStackTrace();
				}

				String id = fileService.insertUpload(fileUuidName, realName, filePath);
				msg = "上传成功";
				map.put("id", id);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			msg = "文件为空";
		}
		map.put("msg", msg);
		return map;

	}
	
	@RequestMapping(value ="/file/img")
	public String getImg(){
		
		return "";
	}
	
	public static void main(String[] args) {
		String b="a";
		String a= "a";
		System.out.println(b.equals(a));
	}

}
